﻿using System;
using System.Globalization;
using System.Windows.Controls;

namespace XamlTorrent.Common.Validation
{
    public class IntegerValidationRule : ValidationRule
    {
        public IntegerValidationRule()
        {
        }

        private int _min = int.MinValue;
        private int _max = int.MaxValue;

        public int Min
        {
            get { return _min; }
            set { _min = value; }
        }

        public int Max
        {
            get { return _max; }
            set { _max = value; }
        }


        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            int number;
            try
            {
                number = int.Parse(value.ToString(), NumberStyles.Integer);
            }
            catch (Exception e)
            {
                return new ValidationResult(false, 
                    String.Concat("Value contains illegal characters or ", e.Message)
                    );
            }

            if (number < Min || number > Max)
            {
                return new ValidationResult(false,
                  String.Format("Value must be between {0} and {1} inclusive.", Min, Max)
                  );
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }
    }
}
